package study.zhangbo.lock.distributed.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import study.zhangbo.lock.distributed.IBaseLockService;

/**
 * Created by zhangbo on 2020/10/28.
 */
@Service
public class RedisLockService implements IBaseLockService {


    @Autowired
    private RedisLockUtils lockUtils;


    private static final ThreadLocal<RedisLock> THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 加锁
     * @param lockName
     */
    @Override
    public void lock(String lockName) {
        RedisLock redisLock = new RedisLock(lockName,lockUtils);
        THREAD_LOCAL.set(redisLock);
        redisLock.lock();
    }

    /**
     * 锁释放
     */
    @Override
    public void unlock() {
        RedisLock redisLock = THREAD_LOCAL.get();
        if(null != redisLock) {
            redisLock.unlock();
            THREAD_LOCAL.remove();
        }
    }
}
